package com.ts.utils

import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.view.Surface
import android.view.SurfaceView
import android.widget.RelativeLayout

class splayer {


    init {
        System.loadLibrary("audiocamera")

    }
    var surfaceView:SurfaceView?= null
    constructor(surfaceView:SurfaceView){
      this.surfaceView=surfaceView
    }

    external fun play(url: String?, surface: Surface?)

    public fun onSizeChange( width:Int, heigth:Int) {

        val ratio = width / heigth.toFloat()
        val screenWidth = surfaceView!!.context.resources.displayMetrics.widthPixels
        var videoWidth = 0
        var videoHeigth = 0
        videoWidth = screenWidth
        videoHeigth = (screenWidth / ratio).toInt()
        val lp = RelativeLayout.LayoutParams(videoWidth, videoHeigth)
        surfaceView!!.layoutParams = lp //调整surfaceview控件的大小


    }

    //    byte[] buffer
    //     uint8_t *outbuffer   是 1 不是2
    //    响应数据  解码音频 数据
    fun playTrack(buffer: ByteArray?, lenth: Int) {
        if (audioTrack != null && audioTrack!!.playState == AudioTrack.PLAYSTATE_PLAYING) {
//播放声音   audioTrack.write(0,0,1） 播放声音
            audioTrack!!.write(buffer!!, 0, lenth)
        }
    }
    private var audioTrack: AudioTrack? = null
    fun createTrack(sampleRateInHz:Int,nb_channals:Int){
        var channaleConfig=0;

        if (nb_channals==1){
            channaleConfig = AudioFormat.CHANNEL_OUT_MONO
        } else if (nb_channals == 2) {
            channaleConfig = AudioFormat.CHANNEL_OUT_STEREO
        } else {
            channaleConfig = AudioFormat.CHANNEL_OUT_MONO
        }
        val buffersize = AudioTrack.getMinBufferSize(
            sampleRateInHz,
            channaleConfig, AudioFormat.ENCODING_PCM_16BIT
        )
        audioTrack = AudioTrack(
            AudioManager.STREAM_MUSIC, sampleRateInHz,
            channaleConfig,
            AudioFormat.ENCODING_PCM_16BIT,
            buffersize,
            AudioTrack.MODE_STREAM
        )
        audioTrack?.play()
    }
}